$(function() {
    var extendAddIndex = 1;
    // 初始化数据(点击之后再执行此逻辑)
    $.ajax({
        url: 'http://120.24.1.204:8080/goodsType/edit',
        dataType: 'jsonp',
        data: {
            typeId: 10
        },
        success: function(res) {
            // 添加品牌
            var pinpaiHtml = '';
            $.each(res.allBrands, function(i, n){
                pinpaiHtml += '<label class="checkbox">\
                                <input type="checkbox" value="'+n.brandId+'">'+n.brandName+'\
                            </label>';
            });
            $('[data-style="glpp"]').html(pinpaiHtml);


            // 选中关联品牌
            var glppValueInput = $('[data-style="glpp"] input');
            var checkedBrandIdsArr = res.checkedBrandIds.split(',');
            for(var i = 0, len = glppValueInput.length;i < len;i++) {
                var val = glppValueInput.eq(i).val();
                for(var j = 0,l = checkedBrandIdsArr.length; j < l;j++) {
                    if(checkedBrandIdsArr[j] == val) {
                        glppValueInput.eq(i).attr("checked",'checked');
                    }
                }
            }

            // 基本设置
            $('[data-role="shopName"]').val(res.goodsType.name);
            $('[data-role="shopAlias"]').val(res.goodsType.alias);

            // 扩展属性
            var extendHtml = '';
            var typePropsList = res.typePropsList;
            for(var i = 0, len = typePropsList.length;i < len;i++) {

                extendHtml += '<tr data-index="'+extendAddIndex+'">\
                                    <td>\
                                        <input type="text" name="name" data-role="extendName" value="'+typePropsList[i].name+'">\
                                    </td>\
                                    <td>\
                                        <input type="text" name="name" data-role="extendAlias" value="'+((typePropsList[i].alias)?typePropsList[i].alias:'')+'">\
                                    </td>\
                                    <td>\
                                        <select class="" name=""  data-role="extendStyle">';
                                if(typePropsList[i].type == 1) {
                                    extendHtml += '<option value="1" selected="selected">渐进式筛选</option>\
                                                    <option value="2">下拉筛选</option>\
                                                    <option value="3">不可筛选</option>';
                                } else if(typePropsList[i].type == 2) {
                                    extendHtml += '<option value="1">渐进式筛选</option>\
                                                    <option value="2" selected="selected">下拉筛选</option>\
                                                    <option value="3">不可筛选</option>';
                                } else if(typePropsList[i].type == 3) {
                                    extendHtml += '<option value="1">渐进式筛选</option>\
                                                    <option value="2">下拉筛选</option>\
                                                    <option value="3" selected="selected">不可筛选</option>';
                                }

                                // ---------
                                var listItem = typePropsList[i].typePropsValueList;
                                var listItemStr = '';
                                var listItemArr = [];
                                for(var k = 0, l = listItem.length;k < l;k++) {
                                    listItemArr.push(listItem[k].name)
                                }
                                listItemStr = listItemArr.join(','),
                                extendHtml += '</select>\
                                    </td>\
                                    <td>\
                                        <span class="ws-btn" data-role="extendAdd'+extendAddIndex+'" data-id="'+extendAddIndex+'">\
                                            <i class="ico-edit"></i>\
                                            增加选择项\
                                        </span>\
                                        <span>'+listItemStr+'</span>\
                                    </td>\
                                    <td>';
                                    if(typePropsList[i].show == 1) {
                                        extendHtml += '<input type="checkbox" name="name" data-role="extendShow" checked="checked">';
                                    } else {
                                        extendHtml += '<input type="checkbox" name="name" data-role="extendShow">';
                                    }

                                    extendHtml += '</td>\
                                    <td>\
                                        <input type="text" name="name" data-role="extendOrder" value="'+typePropsList[i].ordernum+'">\
                                    </td>\
                                    <td>\
                                        <i class="ico-del" data-role="trDel"></i>\
                                    </td>\
                                </tr>';
                            // $('body').append(extendAddHtml(extendAddIndex,typePropsList[i].typePropsValueList));
                            // extendAddPop(extendAddIndex);
                            extendAddIndex++;

            }

          $('[data-role="extend"]').html(extendHtml);

          // 规格
          var specListHtml = '';
          for(var i = 0, len = res.specList.length;i < len;i++) {
              specListHtml += '<tr>\
                                  <td>'+res.specList[i].specName+'</td>\
                                  <td>\
                                      <select class="" name="" data-role="specstyle">';
              if(res.specList[i].specShowType == 1) {
                  specListHtml += '<option value="1" selected="selected">可筛选-平铺显示</option>\
                                  <option value="2">可筛选-下拉显示</option>\
                                  <option value="3">不作为筛选项</option>';
              } else if(res.specList[i].specShowType == 2) {
                  specListHtml += '<option value="1">可筛选-平铺显示</option>\
                                  <option value="2" selected="selected">可筛选-下拉显示</option>\
                                  <option value="3">不作为筛选项</option>';
              } else if(res.specList[i].specShowType == 3) {
                  specListHtml += '<option value="1">可筛选-平铺显示</option>\
                                  <option value="2">可筛选-下拉显示</option>\
                                  <option value="3" selected="selected">不作为筛选项</option>';
              }

              specListHtml += '</select>\
                                  </td>\
                                  <td>\
                                      <i class="ico-asc-float" data-role="trUp"></i>\
                                      <i class="ico-desc-float" data-role="trDown"></i>\
                                      <i class="ico-del-float" data-role="trDel"></i>\
                                  </td>\
                              </tr>';
          }
          $('[data-role="typeSpecJson"]').html(specListHtml);

        },
        error: function() {

        }
    });
    $(document).on('click', '[data-role="extendChooseBtn"]', function() {
        extendChooseHtml = '<tr>\
                                <td>\
                                    <input type="text" name="name" value="">\
                                </td>\
                                <td>\
                                    <i class="ico-asc-float" data-role="trUp"></i>\
                                    <i class="ico-desc-float" data-role="trDown"></i>\
                                    <i class="ico-del-float" data-role="trDel"></i>\
                                </td>\
                            </tr>';
        $('[data-role="extendChoose"]').append(extendChooseHtml)
    })


    var extendAddHtml = function(i, opt) {
        var extendChooseHtml = '';
        if(opt && opt.length) {
            for(var i = 0,len = opt.length;i < len;i++) {
                extendChooseHtml = '<tr>\
                                        <td>\
                                            <input type="text" name="name" value="'+opt[i].name+'">\
                                        </td>\
                                        <td>\
                                            <i class="ico-asc-float" data-role="trUp"></i>\
                                            <i class="ico-desc-float" data-role="trDown"></i>\
                                            <i class="ico-del-float" data-role="trDel"></i>\
                                        </td>\
                                    </tr>';
            }
        }

        return '<div id="extendAdd" class="hide">\
                    <span class="ws-btn ext-add" data-role="extendChooseBtn" data-id="'+i+'"><i class="ico-add"></i>添加可选值</span>\
                    <table class="ws-table" border=1 style="margin: 10px auto 20px;width: 670px;float:left" id="extendAddItem'+i+'">\
                        <thead>\
                            <tr>\
                                <th>\
                                    选择项可选值\
                                </th>\
                                <th>\
                                    操作\
                                </th>\
                            </tr>\
                        </thead>\
                        <tbody data-role="extendChoose"></tbody>\
                    </table>\
                </div>';
    }

    // var extendAddPop = function(i) {
    //     var index = i;
        // 增加选择项
        var styleIndex; // 增加选择项索引
        BUI.use(['bui/overlay','bui/form'],function(Overlay,Form){

         var dialog = new Overlay.Dialog({
               title:'增加选择项',
               width:700,
               height:360,
               //配置DOM容器的编号
               contentId:'extendAdd',
               buttons:[{
                    text:'关闭',
                    elCls : 'button',
                    handler : function(){
                        // ------
                        var tr = $('[data-role="extendChoose"] tr');
                        var arr = [];
                        for(var i = 0, len = tr.length;i < len;i++) {
                            arr.push(tr.eq(i).find('input').val().trim());
                        }
                        var value = arr.join(',');
                        $('[data-role="extend"] tr').eq(styleIndex).find('[data-role="extendAdd"]').attr('data-value',value).parent('td').find('span').eq(1).html(value);
                      this.close();
                    }
                  }
                ],
             });
           $(document).on('click','[data-role="extendAdd"]', function () {
               styleIndex = $(this).closest('tr').index();
               $('[data-role="extendChoose"]').html('');
               var valueArr = $(this).attr('data-value').split(',');
               var html = '';
               for(var i = 0, len = valueArr.length;i < len; i++) {
                   html += '<tr>\
                               <td>\
                                   <input type="text" name="name" value="'+valueArr[i]+'">\
                               </td>\
                               <td>\
                                   <i class="ico-asc-float" data-role="trUp"></i>\
                                   <i class="ico-desc-float" data-role="trDown"></i>\
                                   <i class="ico-del-float" data-role="trDel"></i>\
                               </td>\
                           </tr>';
               }
               $('[data-role="extendChoose"]').html(html);
               dialog.show();
           });
         });
    // }
    // 扩展属性添加
    $(document).on('click', '[data-role="extendBtn"]', function() {
        var extendHtml = '<tr data-index="'+extendAddIndex+'">\
                            <td>\
                                <input type="text" name="name" data-role="extendName">\
                            </td>\
                            <td>\
                                <input type="text" name="name" data-role="extendAlias">\
                            </td>\
                            <td>\
                                <select class="" name=""  data-role="extendStyle">\
                                    <option value="1">渐进式筛选</option>\
                                    <option value="2">下拉筛选</option>\
                                    <option value="3">不可筛选</option>\
                                </select>\
                            </td>\
                            <td>\
                                <span class="ws-btn" data-role="extendAdd" data-value="111,222">\
                                    <i class="ico-edit"></i>\
                                    增加选择项\
                                </span>\
                                <span></span>\
                            </td>\
                            <td>\
                                <input type="checkbox" name="name" data-role="extendShow">\
                            </td>\
                            <td>\
                                <input type="text" name="name" data-role="extendOrder">\
                            </td>\
                            <td>\
                                <i class="ico-del" data-role="trDel"></i>\
                            </td>\
                        </tr>';
      $('[data-role="extend"]').append(extendHtml);

    //   $('body').append(extendAddHtml(extendAddIndex));
    //   extendAddPop(extendAddIndex);
      extendAddIndex++;
    })

    var tab2AddData = [];



    //规格弹窗
    BUI.use(['bui/overlay','bui/form'],function(Overlay,Form){

     var dialog = new Overlay.Dialog({
           title:'选择规格',
           width:720,
           height:400,
           //配置DOM容器的编号
           contentId:'size-content',
           success:function () {
             var name = $('#size-contentLeft').find('input:checked').val();
             var html = '<tr>\
                             <td>'+name+'</td>\
                             <td>\
                                 <select class="" name="" data-role="specstyle">\
                                     <option value="1">可筛选-平铺显示</option>\
                                     <option value="2">可筛选-下拉显示</option>\
                                     <option value="3">不作为筛选项</option>\
                                 </select>\
                             </td>\
                             <td>\
                                 <i class="ico-asc-float" data-role="trUp"></i>\
                                 <i class="ico-desc-float" data-role="trDown"></i>\
                                 <i class="ico-del-float" data-role="trDel"></i>\
                             </td>\
                         </tr>';

            $('[data-role="typeSpecJson"]').append(html);
             this.close();
           }
         });

       $('[data-role="chooseSize"]').on('click',function () {
         dialog.show();
       });
     });

     // 添加新规格
     BUI.use(['bui/overlay','bui/form'],function(Overlay,Form){

      var dialog = new Overlay.Dialog({
            title:'增加规格',
            width:700,
            height:360,
            //配置DOM容器的编号
            contentId:'addNewSize',
            success:function () {
              var name = $('[ data-role="addNewSizeName"]').val().trim();
              if(name == '') {
                  alert('规格名称不能为空！');
                  return;
              }
              var alias = $('[ data-role="addNewSizeAlias"]').val().trim();
              var bz = $('[ data-role="addNewSizeBz"]').val().trim();

              var xsfs = $('[data-role="addNewSizeRadio2"] input:checked').val();
              var xslx = $('[data-role="addNewSizeRadio1"] input:checked').val();

              var itemName = [];
              var itemAlias = [];
              var itemNameTr = $('[data-role="sizeW"] tr');
              var itemNameLen = itemNameTr.length;
              var specValuesJson = [];

              for(var i = 0; i < itemNameLen;i++) {
                  itemName.push(itemNameTr.eq(i).find('input').eq(0).val());
                  itemAlias.push(itemNameTr.eq(i).find('input').eq(1).val());
                  var obj = {}
                  obj.specValue = itemNameTr.eq(i).find('input').eq(0).val();
                  obj.alias = itemNameTr.eq(i).find('input').eq(1).val();
                  obj.numOrder = i + 1;
                  specValuesJson.push(obj);
              }

              var aliasItem = alias ? "["+alias+"]" : "";
              var leftHtml = '<li class="ws-sizeL_item">\
                              <label>\
                                  <input type="radio" name="name" value="'+name+'"> '+name + aliasItem +'\
                              </label>\
                          </li>';
              $('.ws-sizeL_inner ul').append(leftHtml);

              var rightNameHtml = '';
            for(var i = 0,len = itemName.length;i < len;i++) {
                rightNameHtml += '<div class="ws-text__inner">\
                                    <p>'+itemName[i]+'</p>\
                                </div>';
            }
            var rightHtml = '<li>\
                                <p>'+name+'</p>\
                                <p>\
                                     [显示方式：'+$('[data-role="addNewSizeRadio2"] input:checked').attr('data-value')+']\
                                </p>\
                                <div class="ws-text">'+rightNameHtml+'</div>\
                            </li>';
            $('.ws-sizeR_inner ul').append(rightHtml);

            $.ajax({
                url: 'http://120.24.1.204:8080/specification/editSave',
                dataType: 'jsonp',
                data: {
                    specName: name,
                    specMemo: bz,
                    alias: alias,
                    specType: xslx,
                    specShowType: xsfs,
                    specValuesJson:specValuesJson
                },
                success: function(res) {
                    if(res.code == 0) {
                        alert('添加成功');
                    };
                },
                error: function() {

                }
            })
              this.close();
            }
          });

        $('[data-role="addNewSize"]').on('click',function () {
            $('[ data-role="addNewSizeTop"]').find(':text').val('');
            $('[data-role="addNewSizeRadio1"] input').eq(0).attr("checked",'checked');
            $('[data-role="addNewSizeRadio2"] input').eq(0).attr("checked",'checked');
            $('[ data-role="addNewSizeBottom"] [data-role="sizeW"]').html('');
          dialog.show();
        });
      });



    $(document).on('click', '[data-role="addGoodsSubmit"]', function() {
        // tab1
        var shopName = $('[data-role="shopName"]').val().trim();
        var shopAlias = $('[data-role="shopAlias"]').val().trim();
        var brandsObj = $('[data-role="brands"] input:checked');
        var brandsLen = $('[data-role="brands"] input:checked').length;
        var brandIdsArr = [];
        var brandIds = '';
        for(var i = 0; i < brandsLen; i++) {
            brandIdsArr.push(brandsObj.eq(i).val());
        }
        brandIds = brandIdsArr.join(',');

        if(shopName == '') {
            alert('信息填写不完整！');
            return;
        }

        // tab2-----------
        var typePropsJson = [];
        var extend = $('[data-role="extend"] tr');
        var extendLen = extend.length;
        for(var i = 0;i < extendLen;i++) {
            var extendItem = extend.eq(i);
            var obj = {};
            obj.name = extendItem.find('[data-role="extendName"]').val().trim();
            obj.alias = extendItem.find('[data-role="extendAlias"]').val().trim();
            // obj.type = extendItem.find('[data-role="extendStyle"]').val().trim();
            obj.show = extendItem.find('[data-role="extendShow"]:checked').length ? 1 : 0;
            obj.ordernum = extendItem.find('[data-role="extendOrder"]').val().trim();

            var dataId = extendItem.find('.ws-btn').attr('data-id');
            // var itemTr = $('#extendAddItem'+dataId).find('tbody').find('tr');
            var itemStr = extendItem.find('.ws-btn').attr('data-value') || '' ;
            var typePropsValueList = [];
            var itemArr = itemStr.split(',');
            for(var k = 0, l = itemArr.length;k < l;k++) {
                var o = {};
                o.name = itemArr[k];
                o.ordernum = k;
                typePropsValueList.push(o);
            }

            obj.typePropsValueList = typePropsValueList;
            typePropsJson.push(obj);
        }

        // tab3
        var typeSpecJson = [];
        var ptypeSpecJsonTr = $('[data-role="typeSpecJson"] tr');
        var ptypeSpecJsonTrLen = ptypeSpecJsonTr.length;
        for(var i = 0;i < ptypeSpecJsonTrLen;i++) {
            var extendItem = ptypeSpecJsonTr.eq(i);
            var obj = {};
            obj.specStyle = extendItem.find('[data-role="specstyle"]').val().trim();
            obj.ordernum = i+1;
            typeSpecJson.push(obj);
        }


        // tab4
        var price = [];
        var priceTr = $('[data-role="price"] tr');
        var priceTrLen = priceTr.length;
        for(var i = 0;i < priceTrLen;i++) {
            var extendItem = priceTr.eq(i);
            var obj = {};
            obj.min = extendItem.find('[data-role="min"]').val().trim();
            obj.max = extendItem.find('[data-role="max"]').val().trim();
            price.push(obj);
        }

        // 发送请求
        $.ajax({
            url: 'http://120.24.1.204:8080/goodsType/editSave',
            dataType: 'jsonp',
            data: {
                typeId: 10,
                name: shopName,
                alias: shopAlias,
                brandIds: brandIds,
                typePropsJson: typePropsJson,
                typeSpecJson: typeSpecJson,
                price: price
            },
            success: function(res) {
                if(res.code == 0) {
                    alert('提交成功！');
                }
            },
            error: function() {

            }
        })
    })

    // 获取已有规格
    $.ajax({
        url: 'http://120.24.1.204:8080/specification/queryList',
        dataType: 'jsonp',
        success: function(res) {
            var data = res,
                html = '',
                rightHtml = '';
            for(var i = 0,len = data.length;i < len;i++) {
                var alias = data[i].alias ? ('['+data[i].alias+']') : '';
                if(i == 0) {
                    html += '<li class="ws-sizeL_item">\
                        <label>\
                            <input type="radio" name="name" value="'+data[i].specName+'" checked="checked"> '+data[i].specName+alias+'\
                        </label>\
                    </li>';
                } else {
                    html += '<li class="ws-sizeL_item">\
                        <label>\
                            <input type="radio" name="name" value="'+data[i].specName+'"> '+data[i].specName+alias+'\
                        </label>\
                    </li>';
                }

                var xsfs = data[i].specShowType == 1 ? '平铺显示': '下拉显示';
                var isActive = i == 0 ? 'ws-active' : '';
                rightHtml += '<li class="'+isActive+'">\
                                <p>'+data[i].specName+'</p>\
                                <p>[显示方式：'+xsfs+']</p>\
                                <div class="ws-text">';
                for(var j = 0, l = data[i].specValuesList.length;j < l;j++) {
                    rightHtml += '<div class="ws-text__inner">\
                                    <p>'+data[i].specValuesList[j].specValue+'</p>\
                                </div>';
                }

                rightHtml += '</div></li>';
            }

            $('.ws-sizeL_inner ul').html(html);
            $('.ws-sizeR_inner ul').html(rightHtml);
        },
        error: function() {
            alert('请求错误');
        }
    })
})
